<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

class User extends IndexController
{
    public function index()
    {
        $list = DB::table('qq_user')
            ->field('*')
            ->select();

        return view('index/user', [
            'title' => '用户列表',
            'list' => $list
        ]);

    }


    public function edit($id)
    {
        $list = DB::table('qq_user')
            ->where('id=' . $id)
            ->find();

        return view('index/user_edit', [
            'title' => '编辑用户信息',
            'list' => $list
        ]);
    }

    public function doedit()
    {
//        echo '111';
        $file = request()->post();
        $id = $file['id'];
        unset($file['id']);

//        dump($file);
        $data = DB::table('qq_user')
            ->where('id', $id)
            ->update($file);

        if ($data) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    public function qx($id)
    {
        // 查询所有角色
        $data = DB::table('qq_role')
            ->select();


        //遍历



        $list = DB::view(['qq_role'=>'r'],'id')
                ->view(['qq_user_role'=>'ur'],['rid','uid'],['r.id=ur.rid'])
                ->field('r.name')
                ->where('ur.uid',$id)
                ->select();
//        dump($list);
        $role = [];
        foreach ($list as $v){
            $role[] = $v['name'];
        }
//        dump($id);
//        dump($list);
//        dump($role);
//        dump($user['name']);
//        dump($user['id']);

//        die;

        return view('index/qx',[
            'data'=>$data,
//            'nid'=>$user['id'],
            'id'=>$id,
            'role'=>$role
        ]);
    }

    public function doqx()
    {
        $data = input('post.');
        $uid = $data['uid'];
        $role = $data['role'];
//        dump($data);
//        dump($uid);
//        die;
        //清空对应所有角色
        DB::table('qq_user_role')
            ->where('uid',$uid)
            ->delete();

        //插入 遍历

        foreach( $role as $k => $v) {
            $list = ['uid' => $uid, 'rid' => $v];
            DB::table('qq_user_role')
                ->insert($list);
        }
//            dump($role);
//            dump($list);
//        die;


        $this->success('分配成功');
    }


    public function delete($id)
    {
//        return 1111;
        $data = Db::table('qq_user')->where('id',$id)->delete();

        if($data){
            return true;
        }
    }

    public function create()
    {
        return view('index/user_add');
    }

    public function save()
    {
        $list = request()->post();
        $list['userpass'] = md5($list['userpass']);
        $data = DB::table('qq_user')
            ->insert($list);
        if ($data) {
            return $this->success('提交成功', url('index/user/index'));
        } else {
            $this->error('提交失败');
        }
    }
}




